package com.jinlia.show.modules.system.service;

import com.jinlia.show.modules.base.model.po.GoodsAttrPO;
import com.jinlia.show.modules.base.system.entity.GoodsAttr;
import com.jinlia.show.modules.base.system.entity.GoodsAttrValue;
import com.jinlia.show.modules.base.system.service.GoodsAttrMapperService;
import com.jinlia.show.modules.base.system.service.GoodsAttrValueMapperService;
import com.jinlia.show.modules.system.model.forms.GoodsAttrForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GoodsAttrService {
    @Autowired
    private GoodsAttrValueMapperService goodsAttrValueMapperService;
    @Autowired
    private GoodsAttrMapperService goodsAttrMapperService;

    public GoodsAttrForm addOrUpdate(GoodsAttrForm goodsAttrForm) {
        GoodsAttr goodsAttr = goodsAttrForm.getGoodsAttr();
        GoodsAttrValue goodsAttrValue = goodsAttrForm.getGoodsAttrValue();
        //校验重复名
        GoodsAttr oneGoodsAttr = goodsAttrMapperService.lambdaQuery()
                .eq(GoodsAttr::getGoodsId, goodsAttr.getGoodsId())
                .eq(GoodsAttr::getAttrName, goodsAttr.getAttrName())
                .one();
        if (goodsAttr.getId() == null) {
            if (oneGoodsAttr != null) {
                throw new RuntimeException("属性名重复");
            }
            goodsAttrMapperService.save(goodsAttr);
        } else {//修改属性值
            if (oneGoodsAttr != null && !oneGoodsAttr.getId().equals(goodsAttr.getId())) {
                throw new RuntimeException("属性名已存在");
            }else if (oneGoodsAttr == null) {
                goodsAttrMapperService.updateById(goodsAttr);
            }
        }
        goodsAttrValue.setAttrId(goodsAttr.getId());
        goodsAttrValueMapperService.addOrUpdate(goodsAttrValue);
        return goodsAttrForm;
    }

    public GoodsAttrForm del(GoodsAttrForm goodsAttrForm) {
        goodsAttrValueMapperService.removeById(goodsAttrForm.getAttrValueId());
        //删除属性
        Long count = goodsAttrValueMapperService.lambdaQuery()
                .eq(GoodsAttrValue::getAttrId, goodsAttrForm.getAttrId())
                .count();
        if (count == 0 ){
            goodsAttrMapperService.removeById(goodsAttrForm.getAttrId());
        }
        return null;
    }
}
